<script setup lang="ts">
import { reactive, ref, onMounted, toRaw,onBeforeUnmount} from 'vue'
import type { FormInstance } from 'ant-design-vue'
import { UpOutlined, DownOutlined } from '@ant-design/icons-vue'
import {primaryColor_rgb,primaryColorFade} from "@/theme/config"

const formState = reactive<any>({})

const formRef = ref<FormInstance>()

const props = withDefaults(
	defineProps<{
		options: {
			type: 'select' | 'cascader' | 'tree' | 'time' | 'date' | 'date-range' | 'input' | 'number'
			id: string
			props:  {label:string,[key: string]: any }
			innerComponentProps?: { [key: string]: any }
		}[]
		formProps?: { [key: string]: any }
		commitValidate?: boolean
	}>(),
	{
		formProps: () => ({}),
		commitValidate: true,
	}
)

const emits = defineEmits(['reset', 'search', 'collapsed'])

const config = reactive({
	// a-form默认props
	defaultFormProps: { labelCol: { span: 6 }, wrapperCol: { span: 18 }, labelAlign: 'left' },
	// 是否折叠
	isFold: false,
	// form高度
	formHeigh: '',
	// 表单占据的总行数
	rowNum: 1,
	// 表单单行的高度
	rowHeight: 0,
	//  折叠时展示的行数
	defaultRowNum: 1,
	// a-form组件的当前高度
	formComponentHeight:0,
})

const transitionTime=0.2
const transitionTimeStr=transitionTime+'s'

onMounted(() => {
	// console.log(formRef.value)
	setRowHeight()
	setFormHeigth()
})

function setRowHeight(){
	config.formComponentHeight=formRef.value!.$el.clientHeight
	config.rowNum = Math.ceil(props.options.length / 3)
	config.rowHeight = formRef.value!.$el.clientHeight / config.rowNum
}

function setFormHeigth() {
	if (config.isFold) {
		config.formHeigh = config.rowHeight * config.defaultRowNum + 'px'
		setTimeout(()=>{emits('collapsed',parseInt(config.formHeigh)+32)},transitionTime?(transitionTime)*1000:0)
	} else {
		config.formHeigh = config.rowHeight * config.rowNum + 'px'
		emits('collapsed',parseInt(config.formHeigh)+32)
	}
	// 32是操作按钮占据的高度
	// console.log(config.formHeigh)
	
}

function toggle() {
	config.isFold = !config.isFold
	setFormHeigth()
}

function bindReset() {
	// resetFields方法缺陷:手动赋予的值追踪不到，不会被重置，只有手动输入的值才会被重置，但是校验状态可以被重置
	// formRef.value?.resetFields()
	Object.keys(formState).forEach(k=>{
		 if(toRaw(Array.isArray(formState[k])))  formState[k]=[]
		 else formState[k]=''
	})
  formRef.value?.clearValidate()
	emits('reset')
}
function bindSearch() {
	//console.log(config.form)
	if (props.commitValidate)
		formRef
			.value!.validate()
			.then((info: any) => {
					const data=toRaw(formState)
					Object.keys(data).forEach(k=>{
						if(data[k]===undefined || (Array.isArray(data[k]) &&data[k].length==0))
						delete data[k]
					})
					emits('search',data)
			})
			.catch((err: any) => {
				console.log(err)
			})
	else {
		const data=toRaw(formState)
		Object.keys(data).forEach(k=>{
			if(data[k]===undefined || (Array.isArray(data[k]) &&data[k].length==0))
			delete data[k]
		})
		emits('search',data)
	}
	if(props.options.length ==8)
	console.log(toRaw(formState))
}
function handleEnterSearch(e:KeyboardEvent){
	if(e.key=='Enter') bindSearch()
}

function handleRowheightChange(){
	if(formRef.value!.$el.clientHeight!=config.formComponentHeight)
	  {
		setRowHeight()
		setFormHeigth()
	  }
}

window.addEventListener('resize',handleRowheightChange)

onBeforeUnmount(()=>{
	window.removeEventListener('resize',handleRowheightChange)
})
</script>

<template>
	<div class="searchFrom">
		<div class="form" :style="{ height: config.formHeigh }">
			<a-form :model="formState" ref="formRef" v-bind="{ ...config.defaultFormProps, ...props.formProps }"
			:hideRequiredMark="!commitValidate">
				<a-row :gutter="[24]">
					<a-col :span="8" v-for="(item, index) in options" :key="index">
						<a-form-item v-if="item.type === 'select'" v-bind="item.props" style="width: 90%" :name="item.id">
							<a-select v-model:value="formState[item.id]"  v-bind="item.innerComponentProps" :placeholder="'请选择' + item.props.label" allowClear>
							</a-select>
						</a-form-item>

						<a-form-item style="width: 90%" v-if="item.type === 'cascader'" v-bind="item.props" :name="item.id">
							<a-cascader v-bind="item.innerComponentProps" v-model:value="formState[item.id]" :placeholder="'请选择' + item.props.label" allowClear />
						</a-form-item>

						<a-form-item style="width: 90%" v-if="item.type === 'tree'" v-bind="item.props" :name="item.id">
							<a-tree-select v-bind="item.innerComponentProps" v-model:value="formState[item.id]" :placeholder="'请选择' + item.props.label" allowClear />
						</a-form-item>

						<a-form-item style="width: 90%" v-if="item.type === 'time'" v-bind="item.props" :name="item.id">
							<a-time-picker v-bind="item.innerComponentProps" style="width: 100%" v-model:value="formState[item.id]" allowClear />
						</a-form-item>

						<a-form-item style="width: 90%" v-if="item.type === 'date'" v-bind="item.props" :name="item.id">
							<a-date-picker v-bind="item.innerComponentProps" style="width: 100%" v-model:value="formState[item.id]" allowClear />
						</a-form-item>

						<a-form-item style="width: 90%" v-if="item.type === 'date-range'" v-bind="item.props" :name="item.id">
							<a-range-picker v-bind="item.innerComponentProps" v-model:value="formState[item.id]" style="width: 100%"  allowClear />
						</a-form-item>

						<a-form-item style="width: 90%" v-if="item.type === 'input'" v-bind="item.props" :name="item.id">
							<a-input v-bind="item.innerComponentProps" v-model:value="formState[item.id]" :placeholder="'请输入' + item.props.label" allowClear @keyup="handleEnterSearch" />
						</a-form-item>

						<a-form-item style="width: 90%" v-if="item.type === 'number'" v-bind="item.props" :name="item.id">
							<a-input-number v-bind="item.innerComponentProps" style="width: 100%" v-model:value="formState[item.id]" :placeholder="'请输入' + item.props.label" allowClear @keyup="handleEnterSearch" />
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</div>

		<div class="operate" >
			<a-button style="margin-right: 5px" @click="bindReset" > 重置 </a-button>
			<a-button type="primary" @click="bindSearch" > 查询 </a-button>
			<div style="margin-left: 8px; cursor: pointer; user-select: none" @click="toggle" 
			v-if="options.length > 3 * config.defaultRowNum">
				<span :style="{color: primaryColor_rgb}">{{ config.isFold ? '展开' : '折叠' }}</span>
				<span>
					<down-outlined v-show="config.isFold" :style="{color: primaryColor_rgb}" />
					<up-outlined v-show="!config.isFold" :style="{color: primaryColor_rgb}" />
				</span>
			</div>
		</div>
	</div>
</template>

<style scoped lang="less">
.searchFrom {
	// padding: 10px 20px;
	.form {
		overflow: hidden;
		transition: height v-bind(transitionTimeStr);

		:deep(.ant-select-selection-overflow) {
			flex-wrap: nowrap;
			overflow: hidden;
		}
		:deep(.ant-form-item){
			margin-bottom: 10px;
		}
	}

	.operate {
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}
}
</style>
